#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
低位龙头股Web路由
处理低位龙头股分析结果的展示
"""

import os
import json
import logging
from datetime import datetime
from flask import Blueprint, render_template, jsonify

# 导入增强版龙头股分析器
from src.analyzers.enhanced_leading_stock_analyzer import EnhancedLeadingStockAnalyzer

# 创建蓝图
low_position_bp = Blueprint('low_position', __name__, template_folder='templates')

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

@low_position_bp.route('/low-position-leaders')
def low_position_leaders():
    """
    展示低位龙头股分析页面
    """
    try:
        # 获取最新的低位龙头股分析结果
        result_dir = os.path.join('data', 'results', 'low_position_leaders')
        
        # 预测的低位龙头股数据
        predicted_leaders = []
        predicted_files = [f for f in os.listdir(result_dir) if f.startswith('predicted_low_leaders_') and f.endswith('.json')]
        
        if predicted_files:
            latest_predicted_file = max(predicted_files)
            with open(os.path.join(result_dir, latest_predicted_file), 'r', encoding='utf-8') as f:
                predicted_leaders = json.load(f)
                
            # 获取更新时间
            update_time = datetime.strptime(latest_predicted_file.split('_')[-1].split('.')[0], "%Y%m%d").strftime("%Y年%m月%d日")
        else:
            update_time = datetime.now().strftime("%Y年%m月%d日")
        
        # 候选低位龙头股数据
        candidates = []
        candidate_files = [f for f in os.listdir(result_dir) if f.startswith('low_position_leaders_') and f.endswith('.json')]
        
        if candidate_files:
            latest_candidate_file = max(candidate_files)
            with open(os.path.join(result_dir, latest_candidate_file), 'r', encoding='utf-8') as f:
                candidates = json.load(f)
                
        # 渲染模板
        return render_template(
            'low_position_leaders.html',
            predicted_leaders=predicted_leaders,
            candidates=candidates,
            update_time=update_time
        )
        
    except Exception as e:
        logger.error(f"展示低位龙头股分析页面失败: {e}")
        return jsonify({"error": str(e)}), 500

@low_position_bp.route('/api/low-position-leaders')
def api_low_position_leaders():
    """
    提供低位龙头股分析数据的API
    """
    try:
        # 获取最新的低位龙头股分析结果
        result_dir = os.path.join('data', 'results', 'low_position_leaders')
        
        # 预测的低位龙头股数据
        predicted_leaders = []
        predicted_files = [f for f in os.listdir(result_dir) if f.startswith('predicted_low_leaders_') and f.endswith('.json')]
        
        if predicted_files:
            latest_predicted_file = max(predicted_files)
            with open(os.path.join(result_dir, latest_predicted_file), 'r', encoding='utf-8') as f:
                predicted_leaders = json.load(f)
        
        # 候选低位龙头股数据
        candidates = []
        candidate_files = [f for f in os.listdir(result_dir) if f.startswith('low_position_leaders_') and f.endswith('.json')]
        
        if candidate_files:
            latest_candidate_file = max(candidate_files)
            with open(os.path.join(result_dir, latest_candidate_file), 'r', encoding='utf-8') as f:
                candidates = json.load(f)
                
        # 返回JSON数据
        return jsonify({
            "predicted_leaders": predicted_leaders,
            "candidates": candidates,
            "update_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        })
        
    except Exception as e:
        logger.error(f"提供低位龙头股分析数据API失败: {e}")
        return jsonify({"error": str(e)}), 500

@low_position_bp.route('/api/analyze-low-position-leaders')
def analyze_low_position_leaders():
    """
    触发低位龙头股分析过程
    """
    try:
        # 初始化增强版龙头股分析器
        analyzer = EnhancedLeadingStockAnalyzer()
        
        # 分析低位龙头股
        candidates = analyzer.find_low_position_leaders(top_n=15)
        
        # 预测下一批低位龙头股
        predictions = analyzer.predict_next_low_position_leaders(count=8)
        
        return jsonify({
            "status": "success",
            "message": f"成功分析得到{len(candidates)}只候选低位龙头股和{len(predictions)}只预测的低位龙头股"
        })
        
    except Exception as e:
        logger.error(f"触发低位龙头股分析过程失败: {e}")
        return jsonify({"error": str(e)}), 500 